package com.film.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.film.dao.UserDao;
import com.film.exception.MyException;
import com.film.po.User;
import com.film.service.UserService;

/**
 * 用户
 * @author YH
 *
 */

@Service
public class UserServiceImpl implements UserService {

	private UserDao userDao;
	
	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	

	@Transactional
	@Override
	public User add(User user) {
		int result = userDao.insertNonEmptyUser(user);
		if(result!=1) {
			throw new MyException("添加用户失败，用户账户："+user.getUsername());
		}
		
		User user2 = userDao.selectUserById(user.getUserId());
		if(user2==null) {
			throw new MyException("查询用户失败，用户id:"+user.getUserId());
		}
		return user2;
	}

	@Transactional
	@Override
	public void deleteById(int id) {
		int result = userDao.deleteUserById(id);
		if(result!=1) {
			throw new MyException("删除用户失败，用户id："+id);
		}
	}

	@Transactional
	@Override
	public User update(User user) {
		User user2 = userDao.selectUserById(user.getUserId());
		
		if(user2==null) {
			throw new MyException("要更新的用户不存在，用户id:"+user.getUserId());
		}
		
		user2.setName(user.getName());
		user2.setPassword(user.getPassword());
		user2.setUsername(user.getUsername());
		
		int result = userDao.updateNonEmptyUserById(user2);
		
		if(result!=1) {
			throw new MyException("更新用户失败，用户id："+user.getUserId());
		}
		
		User user3 = userDao.selectUserById(user.getUserId());
		
		if(user3==null) {
			throw new MyException("查找的用户不存在，用户id:"+user.getUserId());
		}
		
		return user3;
	}

	@Override
	public User findById(int id) {
		User user = userDao.selectUserById(id);
		if(user==null) {
			throw new MyException("要查找的用户不存在，用户的id:"+id);
		}
		return user;
	}

	@Override
	public List<User> getList() {
		List<User> list = userDao.selectUser();
		
		if(list==null || list.size() <1){
			throw new MyException("查询用户的列表失败");
		}
		return list;
	}


	@Override
	public User findByUsername(String username) {
		User user = userDao.selectUserByUsername(username);
		if(user==null) {
			throw new MyException("要查找的用户不存在，用户名:"+username);
		}
		return user;
	}

}
